<?php

namespace app\components;

use app\models\ChannelVisit;
use yii\base\Component;
use Yii;

/**
 * 统计相关代码
 * Class StatisticsService
 * @package app\components
 */
class StatisticsService extends Component
{
    /**
     * 方法说明：渠道统计,取ｕｒｌ中的ｓ参数
     * $action 1为打开首页，2为点击下载,3为从ｃｎ跳转
     * 作者：张华杰 blues@lonlife.cn
     * 时间：2017-11-11 11:11 AM
     */
    public static function channel($action = 1)
    {
        //如果没有ｓ参数，则忽略
        $utm = Yii::$app->request->get('s');
        if($utm == null) {
            return false;
        }

        //如果ｕｒｌ中显示指定了action,则覆盖形参中的action
        $url_action = Yii::$app->request->get('action');
        if($url_action != null) {
            $action = $url_action;
        }

        //通过ｃｏｏｋｉｅ判断是否是新访问
        if(isset($_COOKIE["channel-actions-$action"])) {
            return false;
        } else {
            setcookie("channel-actions-$action", true, time() + 86400*365);
        }

        $model = new ChannelVisit();
        $model->ip = $_SERVER['REMOTE_ADDR'];
        $model->utm = $utm;
        $model->action = $action;
        $model->created_at = date('Y-m-d H:i:s');
        $model->created_date = date('Y-m-d');
        return $model->save();
    }
}
